package com.benew.ntt.player;

import android.os.Handler;
import android.os.Looper;

public class MainThreadHandler {

    private final Handler mHandler;

    public MainThreadHandler() {
        mHandler = new Handler(Looper.getMainLooper());
    }

    public <T> T runOnMainThread(MethodWrapper<T> method, T defaultValue) {
        if (isMainThread()) {
            return method.invoke();
        } else {
            ObjectWrapper<T> wrapper = new ObjectWrapper<>();
            mHandler.post(() -> wrapper.set(method.invoke()));
            return defaultValue == null ? null : wrapper.get();
        }
    }


    public interface MethodWrapper<T> {
        T invoke();
    }


    private boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }
}
